package com.study.queue;

import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.apache.zookeeper.CreateMode;

import java.io.*;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Created By gtx on 2017/8/12/10:30
 */
public class CuratorQueue<T> implements Queue<T> {

    private String queue_node;

    public CuratorQueue() {
        this.queue_node = CuratorClientFactory.QUEUE_NODE;
    }

    public boolean add(T t){
        try {
            if (curatorFramework.checkExists().forPath(queue_node) == null){
                curatorFramework.create().withMode(CreateMode.PERSISTENT).
                        forPath(queue_node, SerializableSerializer.serialize(t));
            }
            curatorFramework.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).
                    forPath(queue_node+"/", SerializableSerializer.serialize(t));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public T element() {
        try {
           return (T) SerializableSerializer.deserialize(curatorFramework.getData().forPath(getFirstNode()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public T poll() {
        try {
            String first =getFirstNode();
           T t = (T) SerializableSerializer.deserialize(curatorFramework.getData().forPath(first));
           curatorFramework.delete().forPath(first);
           return t;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public boolean isEmpty() {
        try {
            List<String> childrens = curatorFramework.getChildren().forPath(queue_node);
            return childrens.isEmpty();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public int size() {
        try {
            List<String> childrens = curatorFramework.getChildren().forPath(queue_node);
            return childrens.size();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    private String getFirstNode(){
        try {
            List<String> childrens = curatorFramework.getChildren().forPath(queue_node);
            SortedSet<String> sortedSet=new TreeSet<String>();
            for (String children : childrens){
                sortedSet.add(queue_node+"/"+children);
            }
            String first=sortedSet.first();
            return first;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
